package com.service.task;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.common.DateUtils; 
import com.dao.task.SysMessageMapper;
import com.dao.task.TaskMapper;
import com.model.task.SysMessage;
import com.service.sys.WXService;

@Component
@Configuration // 1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class ScheduleService {
	static final Logger logger = LoggerFactory.getLogger(ScheduleService.class);
	@Autowired
	WXService wxService;

	// 3.添加定时任务
//	@Scheduled(cron = "0 0 8 ? * 4")
	// 或直接指定时间间隔，例如：5秒
	// @Scheduled(fixedRate=5000)
	private void configureTasks() {
		System.err.println("执行静态定时任务时间: " + DateUtils.getCurrentTime());
		try {
			selectTaskMessage();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("configureTasks:{}", e.getMessage());
		}
	}

	@Autowired
	TaskMapper taskMapper;
	@Autowired
	SysMessageMapper sysMessageMapper;

	public void selectTaskMessage() {
		HashMap<String, Object> hashtable = new HashMap<>();
		int week = DateUtils.getWeek(new Date());
		String year = DateUtils.getCurrentYear();
		hashtable.put("week", year + week);
		List<HashMap<String, Object>> list = taskMapper.selectTaskMessage(hashtable);
		logger.info("selectTaskMessage", list);
		sendMessage(list);
	}

	public void sendMessage(List<HashMap<String, Object>> list) {
		for (HashMap<String, Object> hashMap : list) { 
			String users = (String) hashMap.get("WX");
			String num = hashMap.get("num").toString();
			String content = "%s:   您有%s条督办信息需要填报，请前往督办系统填写。";
			content = String.format(content, DateUtils.getCurrentTime(), num + "");
			try {
//				wxUtil.sendTxtMessage("HI5272", content);
				wxService.sendTxtMessage(users, content);
				Thread.sleep(1000);
				SysMessage model = new SysMessage();
				model.setMessageId(UUID.randomUUID().toString());
				model.setMessageReceiveorid(users);
				model.setMessageReceiveortime(DateUtils.getCurrentTime());
				sysMessageMapper.insert(model);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
}
